package blog.webcontroller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import blog.domain.User;
import blog.service.ArticleService;
import blog.service.UserService;

@Controller
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private ArticleService articleService;

	@RequestMapping(value = "/validate", method = RequestMethod.POST)
	public String login(@RequestParam String username,
			@RequestParam String password, Model model,
			HttpSession session) {
		if (userService.validateUser(username, password)) {
			User user = userService.getUser(username);
			articleService.editable(user);
			//model.addAttribute("user", user);
			session.setAttribute("user", user);
		}
		model.addAttribute("articles", articleService.getArticles());
		model.addAttribute("topArticles", articleService.getTopTenArticle());
		model.addAttribute("topComments", articleService.getTopTenComment());
		return "articleList";
	}

	@RequestMapping(value = "/logout/{id}", method = RequestMethod.GET)
	public String logout(@PathVariable int id, Model model, HttpSession session) {
		articleService.unEditable(id);
		session.removeAttribute("user");
		model.addAttribute("articles", articleService.getArticles());
		model.addAttribute("topArticles", articleService.getTopTenArticle());
		model.addAttribute("topComments", articleService.getTopTenComment());
		return "articleList";
	}
}
